package cz.czu.pef.DataModelling;

import java.util.*;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cz.czu.pef.DataModelling.utils.Lazy;

@Entity
@Table(name="TRAINING_TYPES_FOR_ROLE_TYPE")
@Inheritance(strategy = InheritanceType.JOINED)
@ManagedBean
@ViewScoped
@Component
public class TrainingTypeForRoleType extends IdPersistenceObject
{
	private static final long serialVersionUID = 1022257034801724764L;

	@ManyToOne(fetch=FetchType.EAGER, optional=true, targetEntity=TrainingType.class, cascade={CascadeType.PERSIST, CascadeType.MERGE, CascadeType.REFRESH})
	@JoinTable(name="MAP_TT_FRT__TT")
	private TrainingType trainingType;

	@ManyToMany(fetch = FetchType.LAZY, targetEntity = RoleType.class, mappedBy = "traningTypesForRoleTypes") // no cascade!
	private Set<RoleType> roleTypes;

	private long periodicityInSeconds;

	@SuppressWarnings("unused")
	private TrainingTypeForRoleType()
	{
		super();
	}

	public TrainingTypeForRoleType(TrainingType trainingType, long periodicityInSeconds)
	{
		this.trainingType = trainingType;
		this.periodicityInSeconds = periodicityInSeconds;
	}

	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	public Set<RoleType> getRoleTypes()
	{
		return roleTypes;
	}

	public long getPeriodicityInSeconds()
	{
		return periodicityInSeconds;
	}

	
	public void setPeriodicityInSeconds(long periodicityInSeconds)
	{
		this.periodicityInSeconds = periodicityInSeconds;
	}

	
	public TrainingType getTrainingType()
	{
		return trainingType;
	}

	@Lazy
	@Transactional(readOnly=true, propagation=Propagation.REQUIRED)
	@Override
	public String toString()
	{
		StringBuilder builder = new StringBuilder();
		builder.append("TrainingTypeForRoleType [trainingType=");
		builder.append(trainingType);
		builder.append(", roleTypes=");
		builder.append(roleTypes);
		builder.append(", periodicityInSeconds=");
		builder.append(periodicityInSeconds);
		builder.append(", toString()=");
		builder.append(super.toString());
		builder.append("]");
		return builder.toString();
	}

	/**
	 * Can be deleted after all related entities are deleted (no cascade).
	 */
	@Override
	public boolean canBeRemoved()
	{
		return getRoleTypes().size() == 0;
	}
}
